#include "InetAddress.h"
#include <strings.h>
#include <cstring>

InetAddress::InetAddress(const uint16_t port, const std::string& ip)
{
  bzero(&m_addr, sizeof(m_addr));
  m_addr.sin_family = AF_INET;
  m_addr.sin_port = htons(port);
  m_addr.sin_addr.s_addr = inet_addr(ip.c_str());
}

std::string InetAddress::toIp() const
{
  char buf[64] = {0};
  ::inet_ntop(AF_INET, &m_addr, buf, sizeof(buf));
  return std::string(buf);
}
std::string InetAddress::toIpPort() const
{
  char buf[64] = {0};
  ::inet_ntop(AF_INET, &m_addr, buf, sizeof(buf));
  uint16_t port = ntohs(m_addr.sin_port);
  sprintf(buf + strlen(buf), ":%u", port);
  return std::string(buf);
}
uint16_t InetAddress::toPort() const
{
  return ntohs(m_addr.sin_port);
}


// #include <iostream>

// int main() {
//   InetAddress addr(8080);
//   std::cout << "IP: " << addr.toIp() << std::endl;
//   std::cout << "IP:PORT " << addr.toIpPort() << std::endl;
//   std::cout << "PORT: " << addr.toPort() << std::endl;
//   return 0;
// }